<!DOCTYPE html>
<meta charset="utf-8">
<style>
 
    .states :hover {
        fill: red;
        stroke-width: 2px;
    }
 
    .state-borders {
        fill: none;
        stroke: #fff;
        stroke-width: 0.5px;
        stroke-linejoin: round;
        stroke-linecap: round;
        pointer-events: none;
    }
</style>
<svg id="cy" width="900" height="600" style="border:1px gainsboro solid"></svg>
<script src="d3.v4.min.js"></script>
<script type="text/javascript" src="leaflet.js"></script>

<script src="topojson.v2.min.js"></script>

<script>
	var colorArr = [], colorArrRev = [];
	for (var i=0;i<20;i++){
		colorArr[i] = bg3();
		colorArrRev[i] = reverseBg3;
	}
	function bg3(){
		var r=Math.floor(Math.random()*256);
		var g=Math.floor(Math.random()*256);
		var b=Math.floor(Math.random()*256);
		return "rgb("+r+','+g+','+b+")";//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
	}
	function reverseBg3(){
		var r=255-Math.floor(Math.random()*256);
		var g=255-Math.floor(Math.random()*256);
		var b=255-Math.floor(Math.random()*256);
		return "rgb("+r+','+g+','+b+")";
	}
	

	
    var svg = d3.select("svg"),
            width = svg.attr("width"),
            height = svg.attr("height");
 
    var projection = d3.geoMercator()
            .center([110, 31])
            .scale(750)
            .translate([width/2, height/2+height/6])
    var path = d3.geoPath()
            .projection(projection);
 
    d3.json("china.json", function(error, cn) {
        if (error) throw error;
		
        svg.append("g")
                .attr("class", "province")
                .selectAll("path")
                .data(cn.features)
                .enter()
				.append("path")
                .attr('stroke','white')
                .attr('fill','lightgray')
                .attr("d", path)
                .append('title')
                .text(function(d){
                    return d.properties.name
                });
 
        svg.append("path")
                .attr("class", "state-borders")
                .attr("d", path(topojson.mesh(cn, cn, function(a, b) { return a !== b; })));
		
		
		var lineFunction = d3.line()
			.x( function(d) {
				//console.log("x postion is  :  " + d[0]);
				return d[0];
		    })
			.y( function(d) {
				//console.log("y postion is  :  " + d[1]);
				return d[1]; 
			});
			//.curve(d3.curveBasis);
			
		var points = [];
		var lineFunction2 = function(lineList){
			var dataList = [];
			var datas = [];
			for(var i = 0; i < lineList.length; i++){
				var cityInfos = lineList[i].TrainTimeTable.Passed_Station_Info;
				for(var j = 0; j < cityInfos.length; j++){
					city = cityInfos[j];
					//console.log("city.gc_station_name is  : " + city.gc_station_name + "city.gc_station_x is  : " + city.gc_station_x + "," +  "city.gc_station_y is ： " + city.gc_station_y)
					datas.push(
						projection([city.gc_station_x, city.gc_station_y])
					);
					points.push(
						projection([city.gc_station_x, city.gc_station_y])
					);
					
				}
				dataList.push(datas);
				datas = [];
			}
			return dataList;
		}
		
		d3.json("http://localhost:5000/getStationInfosByTrainCode/09:00/", function(err, lineList){
			//if (err) throw err;
			//var cityList = cities.elements.nodes;
			var datas = lineFunction2(lineList);
			//.log("line datas is  :  " + datas);
			//从此处得到了所有城市点坐标，用datas集合进行描线
			for(var i=0;i<datas.length;i++){
				var data = datas[i];
				//console.log(" data is  :  " + data);
				svg.append("g")
				.attr("class", "citylines"+i)
				.append("path")
				.attr("d", lineFunction(data))
				.attr("stroke", colorArr[i]) //颜色
				.attr("fill", "none")
				.attr("stroke-width", "2")
				.append('title')
				.text(lineList[i].TrainTimeTable.train_code);
			}
			
			//描点，将
			var keyTimes = [], keyPoints = [];
			
			var train_codes = [];
			for(var i=0;i<lineList.length;i++){
				var keyTime = [], keyPoint = [], totalSpending = 0;
				
				var train_code = lineList[i].TrainTimeTable.train_code;
				var time_spending = lineList[i].TrainTimeTable.time_spending;
				var cities = lineList[i].TrainTimeTable.Passed_Station_Info;
				svg.append("g")
				.attr("class", "city")
				.selectAll("circle")
				.data(cities)
				.enter()
				.append("circle")
				.attr('stroke','grey')
				.attr('fill', colorArr[i])
				.attr("r", 2)
				.attr("transform", function(d) {
					train_codes.push(train_code);
					totalSpending += parseFloat(d.gc_station_run_time);
					keyTime.push(totalSpending/time_spending);
					keyPoint.push(totalSpending/time_spending);
					if(d.gc_stopover_time != '----'){
						keyPoint.push(totalSpending/time_spending);
						totalSpending += parseFloat(d.gc_stopover_time);
						keyTime.push(totalSpending/time_spending);
					}
					
					//console.log("points data is  : " + projection([d.gc_station_x,d.gc_station_y]))
					return "translate(" + projection([
								d.gc_station_x,
								d.gc_station_y
							]) + ")";
				})
				.append('title')
				.text(function(d){
					return d.gc_station_name;
				});
				keyTimes.push(keyTime);
				keyPoints.push(keyPoint);
			}
			
			
			
			for(var ii = 0 ; ii < keyTimes.length; ii++){
				console.log("当前车次为 ： " + train_codes[ii]);
				console.log("keyTimesi"+[ii]+" is : " + keyTimes[ii]);
				console.log("keyPoints"+[ii]+" is : " + keyPoints[ii]);
			}
			
			for(var i=0;i<datas.length;i++){
				var data = datas[i];
				var time_spending = lineList[i].TrainTimeTable.time_spending;
				
				svg.append("circle")
						.attr("r", 3)
						.attr("fill", colorArrRev[colorArrRev.length - i])
						.append('animateMotion')
						.attr('path', lineFunction(data))
						.attr('rotate', "auto")
						.attr('dur', time_spending + "s")
						//添加keyPoints控制点距
						.attr('keyPonts', keyPoints[i].join(";"))
						//添加keyTimes控制点移动速度
						.attr('keyTimes', keyTimes[i].join(";"))
						.attr('repeatCount', "indefinite"); 
			}
			
			/*
			let zoom = d3.zoom()
			  .scaleExtent([1, 10])
			  //.translateExtent([[0,0], [areaWidth, areaHeight]])
			  .on("zoom", zoomed);


		    let zoomRect = svg.append("rect")
			  .attr("width", width)
			  .attr("height", height)
			  .attr("fill","none")
			  .attr("pointer-events","all")
			  .call(zoom);
			
			svg.call(zoom);
			
			*/
		});
		
    });
 
</script>